<template>
  <div class="content-wrapper-2">
    <loginOut :pageName="t('opticore.pageName')" />

    <div class="search-info">
      <!-- 搜索工作栏 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="168px">
        <el-form-item :label="t('opticore.inspection.searchForm.lineId')" prop="lineId">
          <el-select
            v-model="queryParams.lineId"
            class="!w-160px"
            clearable
            disabled
            placeholder=""
          >
            <el-option
              v-for="item in getIntDictOptions(DICT_TYPE.OPTICORE_LINE)"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('opticore.inspection.searchForm.process')" prop="process">
          <el-select
            v-model="queryParams.processCode"
            class="!w-160px"
            clearable
            disabled
            placeholder=""
          >
            <el-option
              v-for="item in processList"
              :key="item.processCode"
              :label="item.processName"
              :value="item.processCode"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div class="serial-number">
        <el-input
          v-model="serial"
          style="max-width: 600px"
          :placeholder="t('opticore.inspection.placeholder.serialNo')"
          clearable
          class="input-with-select"
          @clear="handleSerialClear"
          @keyup.enter="handleSerialSearchSart"
        >
          <template #prepend>
            <el-select v-model="queryParams.typeId" style="width: 115px" placeholder="请选择类型">
              <el-option
                v-for="dict in getIntDictOptions('detection_type')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="handleSerialSearchSart" />
          </template>
        </el-input>
      </div>

      <!-- 工单信息展示区域 -->
      <div v-if="inspectionData" class="inspection-info">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <span class="info-label">{{ t('opticore.inspection.table.docNo') }}：</span>
              <span class="info-value">{{ inspectionData.docNo }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="info-label">{{ t('opticore.inspection.table.qty') }}：</span>
              <span class="info-value">{{ inspectionData.qty || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="info-label">{{ t('opticore.inspection.table.itemCode') }}：</span>
              <span class="info-value">{{ inspectionData.itemCode }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="info-label">{{ t('opticore.inspection.table.specification') }}：</span>
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="inspectionData.itemSpecification"
                placement="top-start"
              >
                <span class="info-value ellipsis">{{ inspectionData.itemSpecification }}</span>
              </el-tooltip>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="info-table">
      <!-- 检验项目列表 -->
      <div style="margin-top: 10px">
        <h3>{{ t('opticore.inspection.table.inspectionItems') }}</h3>
        <div style="display: flex; margin-top: 20px; justify-content: space-between">
          <el-form-item l:label="t('opticore.inspection.table.inspectionCategory')" prop="typeId">
            <el-select
              v-model="detectionType"
              :placeholder="t('opticore.inspection.placeholder.selectType')"
              class="!w-180px"
              @change="handleDetectionTypeChange"

            >
              <el-option
                v-for="dict in paramsTypes"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <div class="action-buttons">
            <el-button type="success" @click="handleSubmit('pass')">{{
              t('opticore.inspection.table.pass')
            }}</el-button>
            <el-button v-if="queryParams.typeId == 1" type="danger" @click="handleSubmit('no-pass')"
              >{{ t('opticore.inspection.table.noPass') }}
            </el-button>
            <el-button v-if="queryParams.typeId == 2" type="warning" @click="handleSubmit('rework')"
              >{{ t('opticore.inspection.table.rework') }}
            </el-button>
          </div>
        </div>
      </div>

      <div
        class="inspection-table"
        v-if="metricsTitles.length > 0 && metricsItemTableData.length > 0"
      >
        <div class="table-scroll-wrapper" v-show="detectionType == 1">
          <table class="custom-table">
            <thead>
              <tr>
                <!-- 左上角斜线单元格 -->
                <th
                  class="sticky-header sticky-column diagonal-header"
                  style="z-index: 99; width: 250px"
                >
                  <div class="top-text">{{ t('opticore.inspection.table.detection') }}</div>

                  <div class="bottom-text">{{ t('opticore.inspection.table.detectionValue') }}</div>

                  <!-- <img src="/src/assets/imgs/table1.png" alt="" style="width: 100%; height: 56px" /> -->
                </th>
                <!-- 动态列头 -->
                <th v-for="(col, colIndex) in metricsRow" :key="colIndex" class="sticky-header">
                  <div style="display: flex; align-items:  center; justify-content: center; gap: 4px;">
                  <span>{{ col.itemName }}</span>
                  <el-tooltip
                    v-if="col.describe"
                    class="box-item"
                    effect="dark"
                    :content="col.describe"
                    placement="top"
                  >
                    <el-icon style=" position: relative; cursor: pointer;">
                      <QuestionFilled />
                    </el-icon>
                 </el-tooltip>
                </div>
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, rowIndex) in metricsItemTableData" :key="rowIndex">
                <td class="label-cell sticky-column">
                  <span style=" font-size: 14px;color: #606266" v-if="row.isEdit">{{
                    row.label
                  }}</span>
                  <el-input v-else v-model="row.label" />
                  <el-icon class="edit-icon" @click="editRow(row)">
                    <Edit />
                  </el-icon>
                </td>

                <td v-for="(value, colIndex) in row.values" :key="colIndex">
                  <el-input
                    v-if="checkShowInput(rowIndex, colIndex)"
                    v-model="row.values[colIndex]"
                    @blur="handleValueCheck(row, colIndex)"
                    :class="{
                      'error-border': row.statuses[colIndex] === 'NG',
                      'success-border': row.statuses[colIndex] === 'OK'
                    }"
                    :placeholder="t('opticore.inspection.placeholder.detectionValue')"
                  />
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        </div>
            <div
        class="inspection-table"
        v-if="metricsTitles.length > 0 && metricsItemTableDataWg.length > 0"
      >

        <div class="table-scroll-wrapper" v-show="detectionType == 2">
          <table class="custom-table">
            <thead>
              <tr>
                <!-- 左上角斜线单元格 -->
                <th
                  class="sticky-header sticky-column diagonal-header"
                  style="z-index: 99; width: 250px"
                >
                  <div class="top-text">{{ t('opticore.inspection.table.detection') }}</div>

                  <div class="bottom-text">{{ t('opticore.inspection.table.detectionValue') }}</div>

                  <!-- <img src="/src/assets/imgs/table1.png" alt="" style="width: 100%; height: 56px" /> -->
                </th>
                <!-- 动态列头 -->
                <th v-for="(col, colIndex) in metricsRow" :key="colIndex" class="sticky-header">
                  <div style="display: flex; align-items: center;; justify-content: center; gap: 4px;">
                  <span>{{ col.itemName }}</span>
                  <el-tooltip
                    v-if="col.describe"
                    class="box-item"
                    effect="dark"
                    :content="col.describe"
                    placement="top"
                  >
                    <el-icon style=" position: relative; cursor: pointer;">
                      <QuestionFilled />
                    </el-icon>
                 </el-tooltip>
                  </div>
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, rowIndex) in metricsItemTableDataWg" :key="rowIndex">
                <td class="label-cell sticky-column">
                  <span style=" font-size: 14px;color: #606266" v-if="row.isEdit">{{
                    row.label
                  }}</span>
                  <el-input v-else v-model="row.label" />
                  <el-icon class="edit-icon" @click="editRowWg(row)">
                    <Edit />
                  </el-icon>
                </td>

                <td v-for="(value, colIndex) in row.values" :key="colIndex">
                  <el-input
                    v-if="checkShowInput(rowIndex, colIndex)"
                    v-model="row.values[colIndex]"
                    @blur="handleValueCheck(row, colIndex)"
                    :class="{
                      'error-border': row.statuses[colIndex] === 'NG',
                      'success-border': row.statuses[colIndex] === 'OK'
                    }"
                    :placeholder="t('opticore.inspection.placeholder.detectionValue')"
                  />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        </div>
            <div
        class="inspection-table"
        v-if="metricsTitles.length > 0 && metricsItemTableDataOTDR.length > 0"
      >

        <div class="table-scroll-wrapper" v-show="detectionType == 3">
          <table class="custom-table">
            <thead>
              <tr>
                <!-- 左上角斜线单元格 -->
                <th
                  class="sticky-header sticky-column diagonal-header"
                  style="z-index: 99; width: 250px"
                >
                  <div class="top-text">{{ t('opticore.inspection.table.detection') }}</div>

                  <div class="bottom-text">{{ t('opticore.inspection.table.detectionValue') }}</div>

                  <!-- <img src="/src/assets/imgs/table1.png" alt="" style="width: 100%; height: 56px" /> -->
                </th>
                <!-- 动态列头 -->
                <th v-for="(col, colIndex) in metricsRow" :key="colIndex" class="sticky-header">
                  <div style="display: flex; align-items:  center; justify-content: center; gap: 4px;">
                  <span>{{ col.itemName }}</span>
                  <el-tooltip
                    v-if="col.describe"
                    class="box-item"
                    effect="dark"
                    :content="col.describe"
                    placement="top"
                  >
                    <el-icon style=" position: relative; cursor: pointer;">
                      <QuestionFilled />
                    </el-icon>
                 </el-tooltip>
                 </div>
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, rowIndex) in metricsItemTableDataOTDR" :key="rowIndex">
                <td class="label-cell sticky-column">
                  <span style=" font-size: 14px;color: #606266" v-if="row.isEdit">{{
                    row.label
                  }}</span>
                  <el-input v-else v-model="row.label" />
                  <el-icon class="edit-icon" @click="editRowOTDR(row)">
                    <Edit />
                  </el-icon>
                </td>

                <td v-for="(value, colIndex) in row.values" :key="colIndex">
                  <el-input
                    v-if="checkShowInput(rowIndex, colIndex)"
                    v-model="row.values[colIndex]"
                    @blur="handleValueCheck(row, colIndex)"
                    :class="{
                      'error-border': row.statuses[colIndex] === 'NG',
                      'success-border': row.statuses[colIndex] === 'OK'
                    }"
                    :placeholder="t('opticore.inspection.placeholder.detectionValue')"
                  />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="t('opticore.inspection.table.editTypeName')"
      width="300px"
      :close-on-click-modal="false"
    >
      <el-input
        v-model="editingLabel"
        :placeholder="t('opticore.inspection.placeholder.name')"
        @keyup.enter="saveEdit"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue' // 导入图标，这里用Search代替二维码图标
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { InspectionRecordApi } from '@/api/opticore/inspection/record'
import { ProcessInfoApi } from '@/api/opticore/processinfo'
import loginOut from '@/components/loginOut/index.vue'

import { ref, onMounted } from 'vue'
import { Edit,QuestionFilled } from '@element-plus/icons-vue'

// 计算对角线角度
const calculateDiagonalAngle = () => {
  const header = document.querySelector('.diagonal-header')
  if (header) {
    const width = header.offsetWidth
    const height = header.offsetHeight
    const angle = Math.atan(height / width) * (180 / Math.PI)
    const length = Math.sqrt(width * width + height * height)
    document.documentElement.style.setProperty('--diagonal-angle', `${angle}deg`)
    document.documentElement.style.setProperty('--diagonal-width', `${(length / width) * 100}%`)
  }
}

/** 报工记录 列表 */
defineOptions({ name: 'WorkReport' })

// 假设每行4个值列
const metricsRow = ref()
const metricsTitles = ref([])
const metricsTitles1 = ref([])
const metricsTitles2 = ref([])

// 每个检测项的检测值个数
const metricsMaxSize = ref([])

//const metricsItemIdRef = ref([])

// 每行数据
const metricsItemTableData = ref([])
const metricsItemTableDataWg = ref([])
const metricsItemTableDataOTDR = ref([])

const detectionType = ref('')
// 记录每行已输入的检测值数量
const inputCounts = ref({})

const paramsTypes = ref([])

// 编辑对话框相关数据
const editDialogVisible = ref(false)
const editingRow = ref(null)
const editingLabel = ref('')

// 编辑操作
function editRow(row) {
  // editingRow.value = row
  // editingLabel.value = row.label
  // editDialogVisible.value = true

  metricsItemTableData.value = metricsItemTableData.value.map((item) => {
    if (row == item) {
      console.log(1, item)

      return {
        ...item,
        isEdit: !item.isEdit
      }
    } else {
      console.log(2, item)
      return {
        ...item,
        isEdit: true
      }
    }
  })
}



function editRowWg(row) {
  // editingRow.value = row
  // editingLabel.value = row.label
  // editDialogVisible.value = true

  metricsItemTableDataWg.value = metricsItemTableDataWg.value.map((item) => {
    if (row == item) {
      console.log(1, item)

      return {
        ...item,
        isEdit: !item.isEdit
      }
    } else {
      console.log(2, item)
      return {
        ...item,
        isEdit: true
      }
    }
  })
}

function editRowOTDR(row) {
  // editingRow.value = row
  // editingLabel.value = row.label
  // editDialogVisible.value = true

  metricsItemTableDataOTDR.value = metricsItemTableDataOTDR.value.map((item) => {
    if (row == item) {
      console.log(1, item)

      return {
        ...item,
        isEdit: !item.isEdit
      }
    } else {
      console.log(2, item)
      return {
        ...item,
        isEdit: true
      }
    }
  })
}

// 保存编辑
function saveEdit() {
  if (editingRow.value) {
    editingRow.value.label = editingLabel.value
  }
  editDialogVisible.value = false
}

// 控制单元格样式
function getCellClass(status) {
  if (status === 'NG') return 'cell-red'
  if (status === 'OK') return 'cell-green'
  return ''
}

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const serial = ref('') //物料序列号
const productLineList = ref([])
const processList = ref([])
const inspectionData = ref(null) // 存储检验数据
const typeList = ref([
  { label: '首检', value: 1 },
  { label: '工序检', value: 2 }
])
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  serialNo: '',
  lineId: '',
  processCode: '',
  typeId: getIntDictOptions('detection_type')[0].value
})
const queryFormRef = ref() // 搜索的表单

/** 初始化 **/
onMounted(() => {
  fetchProcessList()
  paramsTypes.value = getStrDictOptions(DICT_TYPE.ARGS_VALUE_TYPE)

  // detectionType.value = paramsTypes.value[0]
})

// 监听物料序列号变化
/*watch(serial, async (newVal, oldVal) => {
  if (newVal != oldVal) {
    console.log(newVal)
  }
})*/

// watch(
//   queryParams,
//   (newVal, oldVal) => {
//     metricsItemTableData.value = []
//     if (newVal.processCode) {

//       handleSerialSearch()
//     }
//   },
//   {
//     // immediate: true
//   }
// )

// 获取所有工序
const fetchProcessList = async () => {
  try {
    processList.value = await ProcessInfoApi.fetchProcessDoList()
  } finally {
  }
}
const checkShowInput = (rowIndex: number, colIndex: number) => {
  if (rowIndex + 1 > metricsMaxSize.value[colIndex]) return false
  return true
}

// 检查输入值是否在范围内
const handleValueCheck = (row, colIndex: number) => {
  const value = row.values[colIndex]
  if (!value || !inspectionData.value?.recordItemList) {
    row.statuses[colIndex] = ''
    return
  }

  const item = inspectionData.value.recordItemList[colIndex]
  if (!item) return

  // 如果是非数值类型的检测项，不进行范围校验
  if (item.paramType === '3') {
    row.statuses[colIndex] = ''
    return
  }
  if (isNaN(value)) {
    message.warning(t('opticore.inspection.message.enterValidNumber'))
    row.statuses[colIndex] = 'NG'
    return
  }
  const numValue = parseFloat(value)

  const hasMin = !isNaN(parseFloat(item.paramMin))
  const hasMax = !isNaN(parseFloat(item.paramMax))
  const min = hasMin ? parseFloat(item.paramMin) : null
  const max = hasMax ? parseFloat(item.paramMax) : null

  if (!hasMin && !hasMax) {
    row.statuses[colIndex] = ''
    return
  }

  if ((hasMin && numValue < min) || (hasMax && numValue > max)) {
    const range =
      hasMin && hasMax ? `${min} ~ ${max}` : hasMin ? `>= ${min}` : hasMax ? `<= ${max}` : ''
    message.warning(`${t('opticore.inspection.message.enterValidNumber')}：${range}`)
    // 如果数值不在检验范围之内，输入框边框变红

    row.statuses[colIndex] = 'NG'
  } else {
    row.statuses[colIndex] = 'OK'
  }
}

const startTime = ref('')
const endTime = ref('')

const getCurrentTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const handleDetectionTypeChange=(val)=>{
  detectionType.value=val

  handleSerialSearch()


}

const handleSerialSearchSart=()=>{
    detectionType.value = paramsTypes.value[0].value
    handleSerialSearch()

}

const handleSerialSearch = async () => {
  // 2. 记录开始时间（前端执行时）
  startTime.value = getCurrentTime()
  if (!queryParams.typeId) {
    message.warning(t('opticore.inspection.message.selectType'))
    return
  }

  if (queryParams.typeId === 3) {
    message.warning(t('opticore.inspection.message.featureNotAvailable'))
    return
  }

 
  

  if (!serial.value) {
 
    message.warning(t('opticore.inspection.message.scanSerialNo'))
    return
  }

  // 在这里实现你的逻辑
  //console.log('回车键被按下，触发方法，序列号：', serial.value, detectionType.value)

 


 
  const params = {
    type: queryParams.typeId,
    serialNo: serial.value,
    paramType: detectionType.value
  }
  try {
    const data = await InspectionRecordApi.getInspectionRecordQuery(params)
    if (!data) return
    // 更新状态
    inspectionData.value = data
    queryParams.lineId = data.lineId
    queryParams.processCode = data.processCode
    // 为每个检验项目添加检验结果和状态字段
    if (inspectionData.value.recordItemList && inspectionData.value.recordItemList.length > 0) {
      inspectionData.value.recordItemList.forEach((item) => {
        item.status = ''
      })
    }
    metricsRow.value = data.recordItemList
    metricsTitles.value = data.recordItemList.map((row) => row.itemName)
    metricsMaxSize.value = data.recordItemList.map((row) => row.nums)
    //metricsItemIdRef.value = data.recordItemList.map((row) => row.itemId)

    // 生成表格数据
    const maxNums = Math.max(...data.recordItemList.map((item) => item.nums || 0))

    if (detectionType.value == '1') {
      metricsItemTableData.value = Array.from({ length: maxNums }, (_, i) => ({
        label:  metricsItemTableData.value[i]?.label || `检测值${i + 1}`,
        isEdit: true,
        values: metricsItemTableData.value[i]?.values || Array(metricsTitles.value.length).fill(''),
        statuses:
          metricsItemTableData.value[i]?.statuses || Array(metricsTitles.value.length).fill(''),
        itemIds: data.recordItemList.map((row) => row.itemId)
      }))
    } else if (detectionType.value == '2') {
      metricsItemTableDataWg.value = Array.from({ length: maxNums }, (_, i) => ({
        label:  metricsItemTableDataWg.value[i]?.label || `检测值${i + 1}`,
        isEdit: true,
        values:
          metricsItemTableDataWg.value[i]?.values || Array(metricsTitles.value.length).fill(''),

        statuses:
          metricsItemTableDataWg.value[i]?.statuses || Array(metricsTitles.value.length).fill(''),
        itemIds: data.recordItemList.map((row) => row.itemId)
      }))
    } else {
      metricsItemTableDataOTDR.value = Array.from({ length: maxNums }, (_, i) => ({
        label:  metricsItemTableDataOTDR.value[i]?.label || `检测值${i + 1}`,
        isEdit: true,
        values:
          metricsItemTableDataOTDR.value[i]?.values || Array(metricsTitles.value.length).fill(''),
        statuses:
          metricsItemTableDataOTDR.value[i]?.statuses || Array(metricsTitles.value.length).fill(''),
        itemIds: data.recordItemList.map((row) => row.itemId)
      }))
    }
  } catch (error) {
    inspectionData.value.recordItemList = []
  }
}

const handleSubmit = async (type) => {
  console.log('detectionType.value', detectionType.value)

  console.log('metricsItemTableData', metricsItemTableData.value)
  console.log('metricsItemTableDataWg', metricsItemTableDataWg.value)
  console.log('metricsItemTableDataOTDR', metricsItemTableDataOTDR.value)

  endTime.value = getCurrentTime()
  // if (metricsItemTableData.value.length === 0) {
  //   console.warn('metricsItemTableData.isEmpty')
  //   return
  // }
  // 根据不同类型处理提交逻辑
  const statusMap = {
    pass: 1, // 合格
    'no-pass': 2, // 不合格
    rework: 3,
    scrap: 4 // 报废
  }
  // 检查是否所有检验项都已填写
  /*
    const allFilled = inspectionData.value.recordItemList.every(item => item.detectionValue)
    if (!allFilled) {
    message.warning('请填写所有检验项的检验结果')
    return
  }*/

  if (serial.value === '') {
    message.warning(t('opticore.inspection.message.scanSerialNoToClear'))
    return
  }

  // 这里可以调用创建检验记录的API
  const inspectionRecordVO = {
    serialNo: serial.value, // 序列号（物料编号）
    docNo: inspectionData.value.docNo, // 工单号
    materialsNum: inspectionData.value.itemCode, // 物料品号
    typeId: queryParams.typeId, // 检验类型id（字典维护）
    lineId: queryParams.lineId, // 产线id
    processCode: queryParams.processCode, // 工序id
    status: statusMap[type],
    remark: '', // 备注
    creatorName: JSON.parse(localStorage.getItem('userInfo')).nickname, // 默认值
    //recordDetailList: inspectionData.value.recordItemList
    recordDetailList: [
      ...metricsItemTableData.value,
      ...metricsItemTableDataWg.value,
      ...metricsItemTableDataOTDR.value
    ],

    startTime: startTime.value,
    endTime: endTime.value
  }

  console.log('提交检验结果:', { InspectionRecordVO: inspectionRecordVO })

  await InspectionRecordApi.createInspectionRecord(inspectionRecordVO)

  message.success(t('opticore.inspection.message.submitSuccess'))
  // 提交后可以清空数据
  serial.value = ''
  handleSerialClear()
}

// 处理清空事件
const handleSerialClear = () => {
  // 清空产线和工序
  queryParams.lineId = ''
  queryParams.processCode = ''
  inspectionData.value = null
  metricsItemTableData.value = []
  metricsItemTableDataWg.value = []
  metricsItemTableDataOTDR.value = []

  //console.log('物料序列号已清空，同时清空了产线和工序')
}

// 监听检验类别变化
// watch(
//   detectionType,
//   (newVal, oldVal) => {
//     // if (newVal !== oldVal && oldVal !== '') {
//     // debugger
//     handleSerialSearch()
//     // }
//   },
//   {
//     // immediate: true
//   }
// )

// 监听窗口大小变化和组件挂载时计算角度
onMounted(() => {
  // calculateDiagonalAngle()
  // window.addEventListener('resize', calculateDiagonalAngle)
})
</script>
<style scoped>
.serial-number {
  display: flex;
  padding: 0 20px;
  margin-top: 50px; /* 调整上边距 */
  margin-bottom: 40px;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  text-align: center;
  align-items: center;
  justify-content: center;
}

.report-btn-container {
  margin-bottom: 30px; /* 增加底部间距 */
  text-align: center;
}

.report-btn {
  width: 220px;
  height: 160px;
  font-size: 48px;
}

.serial-input {
  width: 500px; /* 调整宽度 */

  /* height: 50px; 调整高度 */
  font-size: 18px; /* 增大字体 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
}

.execute-type {
  width: 100px; /* 调整宽度 */

  /* height: 50px; */
  font-size: 18px; /* 增大字体 */ /* 调整高度 */
  border: 1px solid #fff;

  /* background: #0483e8; */
}

/* 新增样式 */
.inspection-info {
  padding: 15px;
  margin-top: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  align-items: center;
  color: #666;
}

.info-label {
  font-weight: bold;
  color: #666;
}

.info-value {
  margin-left: 5px;
  color: #666;
}

.inspection-items h3 {
  margin-bottom: 15px;
  font-size: 18px;
  color: #666;
}

.action-buttons {
  float: right;
  text-align: center;
}

.action-buttons .el-button {
  padding: 12px 25px;
  margin: 0 10px;
  font-size: 16px;
}

:v-deep(.el-select) {
  height: 500px !important;
}

.ellipsis {
  display: inline-block;
  width: 200px !important;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* --------------- */

.inspection-table {
  width: 100%;
  margin-top: 10px;
}

/* ✅ 固定宽高的滚动容器 */
.table-scroll-wrapper {
  max-width: 100%; /* 或设置成 800px 等固定值 */
  max-height: 550px; /* 你想固定的表格显示高度 */
  overflow: auto; /* 水平 + 垂直都可以滚动 */

  /* border: 1px solid #ccc; */
}

/* 表格本体 */
.custom-table {
  width: 100%;
  min-width: 600px; /* 保证有横向滚动空间 */
  text-align: center;
  border-collapse: collapse;
  table-layout: fixed;
}

/* 表头、单元格基本样式 */
.custom-table th {
  /* padding: 4px; */
  text-align: center;
  white-space: nowrap; /* 不换行，确保横向可滚 */

  /* border: 1px solid #f8f9fe; */
  border: 1px solid #e2e7f5;
}

.custom-table {
  width: auto; /* 改为自动宽度 */
  min-width: 100%; /* 保证最小宽度填满容器 */
  table-layout: fixed; /* 保持固定布局 */
}

.sticky-header {
  position: sticky;
  z-index: 10;
  height: 60px !important;
  min-width: 200px; /* 设置最小列宽 */
  font-size: 14px;
  font-weight: 500;
  color: #515a6e;
  background: #f8f9fe;
}

.table-scroll-wrapper::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-scroll-wrapper::-webkit-scrollbar-thumb {
  background-color: rgb(144 147 153 / 30%);
  border-radius: 8px;
}

.table-scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: rgb(144 147 153 / 50%);
}

.custom-table tbody tr td {
  height: 70px !important;
  padding-right: 30px;
  padding-left: 30px;
  margin-top: -1px;
  margin-right: -1px;
  text-align: center;
  white-space: nowrap; /* 不换行，确保横向可滚 */

  /* border: 1px solid #E2E7F5; */
  border: 1px solid #e2e7f5 !important;

  .el-input__wrapper {
    border: 1px solid #070707;
  }
}

.custom-table td .el-input__inner {
  border-color: #409eff;
  border-width: 2px;
}

/* 确保下拉菜单显示在最上层 */
.el-select__popper {
  z-index: 100000 !important;
}

/* 斜线表头 */

.diagonal-header {
  position: sticky;
  z-index: 99999;
  width: 15%;
  height: 60px;
  padding: 0;
  overflow: hidden;
  font-size: 14px;
  color: #515a6e;
  background: #f8f9ff;
}

.diagonal-header::before {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: var(--diagonal-width, 104%);
  height: 100%;
  border-top: 1px solid #e2e7f5;
  content: '';
  transform: rotate(var(--diagonal-angle, 13deg));
  transform-origin: top left;
}

/* 文本放角落 */
.top-text {
  position: absolute;
  top: 4px;
  right: 6px;
  z-index: 2;
  font-size: 16px;
  color: #606266;
}

.bottom-text {
  position: absolute;
  bottom: 4px;
  left: 6px;
  z-index: 2;
  font-size: 16px;
  color: #606266;
}

/* ✅ 表头固定（非左上） */
.sticky-header {
  position: sticky;
  top: 0;
  z-index: 10;
  font-size: 14px;
  font-weight: 500;
  color: #515a6e;
  background: #f8f9fe;
}

/* ✅ 左侧 label 固定列 */
.sticky-column {
  position: sticky;
  left: 0;
  z-index: 20;
  background: #FFF;
}

/* 编辑图标 */
.label-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  font-weight: bold;
}

.edit-icon {
  font-size: 16px;
  cursor: pointer;
}

/* 边框高亮 */
.cell-red .el-input__wrapper {
  background-color: #fef0f0;
  border: 1px solid #f56c6c !important;
}

.cell-green .el-input__wrapper {
  background-color: #f0f9eb;
  border: 1px solid #67c23a !important;
}

.content-wrapper-2 {
  /* background-color: #fff; */
  margin: 77px 16px 16px;
}

.search-info {
  padding: 20px;
  background-color: #fff;
}

.info-table {
  padding: 20px;
  margin-top: 20px;
  background-color: #fff;
}

.error-border {
  border: 1px solid #ff4d4f;
  border-radius: 4px;
}

.success-border {
  border: 1px solid #67c23a;
  border-radius: 4px;
}
</style>
